<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { onMounted, PropType, reactive, ref, unref, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { getAllMenuTreeApi } from '@/api/menu'
import { cloneDeep } from 'lodash-es'
import { listToTree } from '@/utils/tree'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    value: 'directory',
    label: t('menu.menuType'),
    component: 'RadioButton',
    componentProps: {
      options: [
        {
          label: t('menu.directory'),
          value: 'directory'
        },
        {
          label: t('menu.menu'),
          value: 'menu'
        },
        {
          label: t('menu.button'),
          value: 'button'
        },
        {
          label: t('menu.api'),
          value: 'api'
        }
      ],
      on: {
        change: (val: string) => {
          setSchema([
            {
              field: 'component',
              path: 'componentProps.disabled',
              value: val !== 'menu'
            }
          ])
          setValue('component', val !== 'menu' ? '#' : cacheComponent.value)
        }
      }
    }
  },
  {
    field: 'parentId',
    label: t('menu.parentMenu'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val && formData.type === 0) {
            setValues({
              component: '##'
            })
          } else if (!val && formData.type === 0) {
            setValues({
              component: '#'
            })
          } else if (formData.type === 1) {
            setValues({
              component: unref(cacheComponent) ?? ''
            })
          }
        }
      },
      slots: {
        default: ({ data }) => {
          return <>{t(data.title)}</>
        }
      }
    },
    optionApi: async () => {
      const res = await getAllMenuTreeApi()
      return listToTree(res.data || [], { pid: 'parentId' })
    }
  },
  {
    field: 'title',
    label: t('menu.title'),
    component: 'Input'
  },
  {
    field: 'name',
    label: t('menu.name'),
    component: 'Input'
  },
  {
    field: 'component',
    label: t('menu.component'),
    component: 'Input',
    componentProps: {
      placeholder: '#为顶级目录，##为子目录',
      on: {
        change: (val: string) => {
          cacheComponent.value = val
        }
      }
    }
  },
  {
    field: 'path',
    label: t('menu.path'),
    component: 'Input'
  },
  {
    field: 'redirect',
    label: t('menu.redirect'),
    component: 'Input'
  },
  {
    field: 'icon',
    label: t('menu.icon'),
    component: 'Input'
  },
  {
    field: 'sort',
    label: t('menu.sort'),
    component: 'InputNumber',
    componentProps: {
      min: 1,
      'step-strictly': true
    }
  },
  {
    field: 'activeMenu',
    label: t('menu.activeMenu'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Switch'
  },
  {
    field: 'hidden',
    label: t('menu.hidden'),
    component: 'Switch'
  },
  {
    field: 'alwaysShow',
    label: t('menu.alwaysShow'),
    component: 'Switch'
  },
  {
    field: 'noCache',
    label: t('menu.noCache'),
    component: 'Switch'
  },
  {
    field: 'breadcrumb',
    label: t('menu.breadcrumb'),
    component: 'Switch'
  },
  {
    field: 'affix',
    label: t('menu.affix'),
    component: 'Switch'
  },
  {
    field: 'noTagsView',
    label: t('menu.noTagsView'),
    component: 'Switch'
  },
  {
    field: 'canTo',
    label: t('menu.canTo'),
    component: 'Switch'
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  title: [required()],
  name: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, setValue, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) return await getFormData()
}

const cacheComponent = ref('')

defineExpose({
  submit
})

const setFormValues = (value: any = {}) => {
  if (!value) return
  const cacheRow = cloneDeep(value)
  cacheComponent.value = cacheRow.type === 'menu' ? cacheRow.component : '#'
  cacheRow.component = cacheComponent.value
  if (!cacheRow.parentId) {
    setSchema([
      {
        field: 'component',
        path: 'componentProps.disabled',
        value: true
      }
    ])
  } else {
    setSchema([
      {
        field: 'component',
        path: 'componentProps.disabled',
        value: false
      }
    ])
  }
  if (cacheRow.type === 'menu') {
    setSchema([
      {
        field: 'component',
        path: 'componentProps.disabled',
        value: false
      }
    ])
  } else {
    setSchema([
      {
        field: 'component',
        path: 'componentProps.disabled',
        value: true
      }
    ])
  }
  setValues(cacheRow)
}

watch(
  () => props.currentRow,
  (value) => setFormValues(value),
  {
    deep: true,
    immediate: true
  }
)

onMounted(() => {
  setFormValues(props.currentRow || {})
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :is-col="false" :schema="formSchema" />
</template>
